import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { setToken } from '../../store/slices/auth';
import { setMenus } from '../../store/slices/menu';
import { login } from '../../services/auth';
import './Login.less';

interface LoginForm {
    phone: string;
    password: string;
}

const Login: React.FC = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [loading, setLoading] = useState(false);

    const handleLogin = async (values: LoginForm) => {
        setLoading(true);
        
        try {
            const response: any = await login(values.phone, values.password);
            console.log("登录响应:", response);
            
            // 检查登录是否成功
            if (response.code === 0) {
                // 获取token和菜单数据
                const token = response.data?.access_token || response.access_token || '';
                
                // 处理菜单数据，去除路径中的转义字符
                let menuData = response.data?.nav || response.nav || [];
                
                // 如果有数据，递归处理路径中的转义斜杠
                if (menuData && menuData.length > 0) {
                    const processMenuPaths = (items: any[]) => {
                        items.forEach(item => {
                            if (item.path) {
                                // 去除路径中的转义字符
                                item.path = item.path.replace(/\\\//g, '/');
                            }
                            if (item.children && item.children.length > 0) {
                                processMenuPaths(item.children);
                            }
                        });
                    };
                    
                    processMenuPaths(menuData);
                }
                
                console.log("处理后的菜单数据:", menuData);
                
                if (!token) {
                    message.error('登录成功但未获取到有效凭证');
                    setLoading(false);
                    return;
                }
                
                // 存储数据
                localStorage.setItem('token', token);
                localStorage.setItem('menuData', JSON.stringify(menuData));
                localStorage.setItem('userinfo', response.userinfo);
                
                // 更新Redux状态
                dispatch(setToken(token));
                dispatch(setMenus(menuData));

                message.success(response.msg || '登录成功');
                
                // 确保导航是异步执行的最后一步
                setTimeout(() => {
                    navigate('/home');
                }, 100);
            } else {
                message.error(response.msg || '登录失败，请检查用户名和密码');
            }
        } catch (error: any) {
            console.error('登录错误:', error);
            message.error(error.response?.data?.msg || '网络错误，请稍后再试');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="login-container">
            <div className="login-box">
                <div className="login-title">向明天</div>
                <div className="login-subtitle">欢迎登录</div>

                <Form
                    name="loginForm"
                    className="login-form"
                    onFinish={handleLogin}
                >
                    <Form.Item
                        name="phone"
                        rules={[{ required: true, message: '请输入用户名' }]}
                    >
                        <Input
                            prefix={<UserOutlined />}
                            placeholder="请输入用户名"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item
                        name="password"
                        rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input
                            prefix={<LockOutlined />}
                            type="password"
                            placeholder="请输入密码"
                            size="large"
                        />
                    </Form.Item>

                    <Form.Item>
                        <Button
                            type="primary"
                            htmlType="submit"
                            className="login-button"
                            loading={loading}
                            size="large"
                            block
                        >
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            <div>游客账号同密码:admin</div>

            </div>
        </div>
    );
};

export default Login;